const fs = require('fs')
var accessLog = fs.createWriteStream('access.log', {
    flags: 'a'
});
var errorLog = fs.createWriteStream('error.log', {
    flags: 'a'
});
const express = require('express')//生成一个express实例app
const path = require('path')
const os = require('os')
const favicon = require('serve-favicon')
const logger = require('morgan')
const cookieParser = require('cookie-parser')
const bodyParser = require('body-parser')
const session = require('express-session')
var app = express();
const serveStatic = require('serve-static')
const serveIndex = require('serve-index')

//引入路由控制
const routes = require('./routes/index')

//引入数据库
const settings = require('./settings')

const flash = require('connect-flash')

const connectMongo = require('connect-mongo')

const MongoStore = connectMongo(session)

// app.use(session({
//     secret: settings.cookieSecret,
//     cookie: {maxAge: 1000 * 60 * 60 * 24 * 30},//30 days
//     url: settings.url
// }));

app.use(session({
    secret: settings.cookieSecret,
    key: settings.db, //cookie name
    cookie: {
        maxAge: 1000 * 60 * 60 * 24 * 30
    }, //30 days
    url: settings.url
}));

// 开发环境 设置服务端口号
// app.set('port', process.env.PORT || 7070);
// 生产环境
app.set('port', process.env.PORT || 80);
// app.set('port', process.env.PORT || 8888);

// //设置views文件夹为存放试图文件目录
// app.set('views', path.join(__dirname, 'views'));

// //设置ejs为模板引擎
// app.set('view engine', 'html')
// app.engine('html', ejs.__express)

// app.use(history({
//     rewrites: [
//         {//访问路径含dist则继续访问
//             from: /^\/questions\/.*$/,
//             to: function (context) {
//                 return context.parsedUrl.pathname;
//             }
//         },
//         {//访问路径不含dist则默认访问/dist/index.html
//             from: /^\/.*$/,
//             to: function (context) {
//                 return '/public/questions/index.html';
//             }
//         },
//         {
//             from: /\/admin\/{0,}$/,
//             to: '/admin/index.html'
//         }
//     ]
// }))


//设置public文件夹为静态文件目录
app.use(express.static(__dirname + '/public'))



// rewrites: [
//     {
//         from: /^\/api\/.*$/,
//         to: function (context) {
//             return context.parsedUrl.path
//         }
//     }
// ],
// verbose: true,
// index: path.join(__dirname, 'public/questions/index.html'),
// index: '/default.html',
// htmlAcceptHeaders: ['text/html', 'application/xhtml+xml']
// index: (req) => {
//     return '/questions/index.html' 
// },


app.use(flash());

//设置favicon图标
// app.use(favicon(__dirname + '/public/favicon.ico'));

//加载日志中间件
app.use(logger('dev'));
app.use(logger({
    stream: accessLog
}));

//加载解析json的中间件
app.use(bodyParser.json({ limit: "2100000kb" }));

//加载解析urlencoded请求体的中间件
app.use(bodyParser.urlencoded({
    extended: true
}));

//加载解析cookie的中间件
app.use(cookieParser());


app.use(function (err, req, res, next) {
    var meta = '[' + new Date() + '] ' + req.url + '\n';
    errorLog.write(meta + err.stack + '\n');
    next();
});

app.get('/questions/*', function (request, response) {
    response.sendFile(path.resolve(__dirname, 'public', 'questions/index.html'))
})
app.get('/admin/*', function (request, response) {
    response.sendFile(path.resolve(__dirname, 'public', 'admin/index.html'))
})

//启用路由控制
routes(app);

// app.use('/*', function (req, res, next) {
//     res.sendFile(path.join(__dirname, 'public/questions/index.html'));
// });

function getIPAdress() {

    var interfaces = os.networkInterfaces();
    for (var devName in interfaces) {
        var iface = interfaces[devName];
        for (var i = 0; i < iface.length; i++) {
            var alias = iface[i];
            if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
                return alias.address;
            }
        }
    }
}
var ipAdress = getIPAdress()

// app.use(serveStatic('public/', {
//     'index': ['index.html']
// }));
// app.use(serveIndex('public/', {
//     'icons': true
// }));

//服务启动成功提示
app.listen(app.get('port'), function () {
    console.log('Express server listening on port http://' + ipAdress + ':' + app.get('port'));
    // var uri = 'http://localhost:' + app.get('port');
    // opn(uri)
});
